<template>
  <!-- 系统通知弹出层 -->
  <div v-if="isRead" class="popups" style="background-color: rgba(0, 0, 0, 0.5);">
    <!-- 以下代码部分保持不变 -->
    <el-main style="width: 33%;  border-radius: .6vh; cursor: pointer; background-color: #fff ">
      <div class="header">
        <img
            src="../../assets/icon_message.png"
            style="width: 3vh;height: 3vh; margin: 2.6vh 1vh"
        />
        <h3>系统通知</h3>
      </div>
      <div>
        <el-carousel trigger="click" height="27vh" :autoplay="false" @change="handleCarouselChange">
          <el-carousel-item
              class="custom-carousel-item"
              style=" display: flex; flex-direction: column; align-items: center; justify-content: center;"
              v-for="(sysNotice, id) in sysNoticeList"
              :key="id"
              :data-item-id="id"
          >
            <div style="padding: 0 2vh ;height: 15vh;line-height: 3vh;color: #444;" class="small" id="level">{{sysNotice.title}}（{{ showLevel(sysNotice.level) }}）:{{sysNotice.noticeContent }}</div>
            <el-button @click="sysNotice.remainingTime!=0?'':isSysNotice(sysNotice.noticeId,$event)" type="success" id="buttonTime" class="disabled" round>
              我已知道了<span v-show="sysNotice.remainingTime!=0">({{ sysNotice.remainingTime }}秒)</span>
            </el-button>
          </el-carousel-item>
        </el-carousel>
      </div>
    </el-main>
  </div>
</template>

<script>
import echarts from "echarts";

export default {
  data() {
    return {
      sysNoticeList: [],
      isRead: false,
      timerInterval: null,
    };
  },
  methods: {
    /**
     * 切换轮播图值的方法
     */
    handleCarouselChange(currentIndex, oldIndex) {
      // currentIndex 是切换后当前轮播项的索引
      // oldIndex 是切换前轮播项的索引
      clearInterval(this.timerInterval);//清除正在运行的计时器
      if (this.sysNoticeList[currentIndex].remainingTime !== 0) {
        this.disable()//禁用按钮
      } else {
        this.enable();//启动按钮
      }
      this.delayStart(this.sysNoticeList[currentIndex].noticeId);
    },
    /**
     * 系统通知弹框
     */
    async noticeContent() {
      // 得到黑名单集合
      const {data: res} = await this.$http.get("/system/sysnotice/isRead");
      if (!res.success) {
        return this.$message.error("获取系统通知列表失败:" + res.data.errorMsg);
      }
      // 初始化每个通知项的相关属性
      res.data.forEach(item => {
        item.timer = 0;
        item.isActive = false;
        item.remainingTime = 10; // 设置初始倒计时时间，可根据需求调整
      });
      //判断是否开启弹窗
      if (res.data.length > 0) {
        this.sysNoticeList = res.data;
        this.isRead = true;
        this.delayStart(this.sysNoticeList[0].noticeId);
      }else {
        // 子传父示例：触发一个自定义事件通知父组件
        this.$emit('noticeViewed');
      }
    },
    /**
     * 单个计时器控制
     */
    delayStart(id) {
      this.sysNoticeList.forEach((obj) => {
        if (obj.noticeId === id) {
          obj.timer = 1;
          obj.isActive = true;
        } else {
          obj.timer = 0;
          obj.isActive = false;
        }
      });
      this.delay(id)
    },
    /**
     * 计时器
     */
    delay(id) {
      const sysNotice = this.sysNoticeList.find((obj) => obj.noticeId === id);
      if (sysNotice.timer === 1 && sysNotice.isActive && sysNotice.remainingTime !== 0) {
        this.timerInterval = setInterval(() => { // 启动新的计时器，并存储其标识符
          if (sysNotice.remainingTime <= 1) {
            clearInterval(this.timerInterval); // 倒计时结束，清除计时器
            this.timerInterval = null; // 重置标识符为 null
            this.enable();//启用按钮
          } else {
            this.disable();//禁用按钮
          }
          sysNotice.remainingTime--;
        }, 1000); // 每秒更新一次倒计时
      }
    },
    /**
     * 禁用'我知道了'按钮
     */
    disable() {
      // 倒计时期间添加禁用类名改变按钮样式，显示秒字
      const buttons = document.querySelectorAll('#buttonTime');
      buttons.forEach(button => {
        button.classList.add('disabled');
        button.classList.remove('countdown-finished');
      });
    },
    /**
     * 启动'我知道了'按钮
     */
    enable() {
      // 倒计时结束后移除倒计时相关类名，恢复按钮样式并隐藏秒字
      const buttons = document.querySelectorAll('#buttonTime');
      buttons.forEach(button => {
        button.classList.remove('disabled');
        button.classList.add('countdown-finished');
      });
    },
    async isSysNotice(id, event) {
      const {data: res} = await this.$http.post("/system/sysnotice/addSysNoticeIs/" + id);
      if (!res.success) {
        return this.$message.error("获取系统通知信息失败:" + res.data.errorMsg);
      }
      const itemId = event.target.closest('[data-item-id]').dataset.itemId;
      // 从sysNoticeList数组中移除对应的数据项，实现关闭当前展示的“页面”效果
      this.sysNoticeList = this.sysNoticeList.filter((_, index) => index !== parseInt(itemId));
      this.disable();//禁用按钮
      // 如果sysNoticeList数组为空，即所有“页面”都关闭了，再关闭整个弹窗
      if (this.sysNoticeList.length === 0) {
        this.isRead = false;
        // 子传父示例：触发一个自定义事件通知父组件
        this.$emit('noticeViewed');
      } else {
        this.delayStart(this.sysNoticeList[0].noticeId)
      }
    },
    /**
     * 显示是否呼叫
     */
    showLevel(num) {
      let call = '';
      if (num === 2) {
        call = '紧级';
      } else if (num === 3) {
        call = '重要';
      } else {
        call = '普通';
      }
      return call;
    },
  },
  created() {
    this.noticeContent();
  },
  mounted() {
  },
};
</script>

<style scoped>
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.popups{
  width: 100%;
  height: 100%;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 100;
}
.popups .el-main{
  background-color: #bfdaf2;
  margin: 33vh auto;
}
.popups .el-main .header{
  display: flex;
  justify-content: center;
}
.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  border: none;
}
.small {
  margin: -20px 60px 30px 60px;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制显示的行数为3行 */
  -webkit-box-orient: vertical;
  overflow: auto; /* 当内容超出时显示滚动条 */

}

.custom-carousel-item {
  transition: all 0.0s ease; /* 这里的 0.5s 就是过渡时间，可以按需调整，ease 是过渡效果的函数，可以换为其他如 linear 等 */
}

/* 按钮禁用（延时期间）时的样式 */
.el-button.disabled {
  background-color: #ccc!important;
  color: #999!important;
  cursor: not-allowed!important;
  border-color: #ccc!important;
  width: 150px;height: 30px
}

/* 倒计时文本（秒字）的样式，初始显示 */
.el-button.countdown-text {
  display: inline;
}

/* 倒计时结束后隐藏秒字的样式 */
.el-button.countdown-finished.countdown-text {
  display: none;
}
.total-box-card .number{
  font-size: 3vh;
  line-height: 6.6vh;
  color: #e66413;
}
.total-box-card .title{
  font-size: 1.8vh;
  color: #5e6d82;
}
.miniBox{
  padding: 2vh 0;
  width: 100%;
  height: 100%;
  border-right: 1px solid #ccc;
  font-size: 2vh;
  text-align: center;
}
.user-box-card .el-row .el-col:last-of-type .miniBox{
  border: none;
}
.miniBox .key{
  color: #999999;
  line-height: 3vh;
  font-size: 1.8vh;
  margin-bottom: 1vh;
}
.miniBox .value{
  color: #5e6d82;
}
</style>